<template>
  <el-dialog
    :title="`${detail.id ? '修改' : '新增'}目录`"
    :visible="showDialog"
    width="500px"
    @close="closeDialog"
    @open="openDialog"
  >
    <el-form
      :model="detail"
      ref="form"
      :rules="rules"
      label-width="80px"
      :inline="false"
      size="normal"
    >
      <el-form-item v-if="!directorysId" label="所属学科" prop="subjectID">
        <el-select
          v-model="detail.subjectID"
          placeholder="请选择"
          size="normal"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" size="normal" prop="directoryName">
        <el-input
          v-model="detail.directoryName"
          placeholder="请输入目录名称"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add as addSubjectApi, update as updateSubjectApi } from '@/api/hmmm/directorys.js'
import { simple as getSubjectList } from '@/api/hmmm/subjects.js'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    directorysId: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      rules: {
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
        subjectID: [{ required: true, message: '请选择所属学科', trigger: 'blur' }]
      },
      options: []
    }
  },
  methods: {
    // 打开弹框
    async openDialog () {
      const { data } = await getSubjectList()
      // console.log(data)
      this.options = data
    },
    // 确认按钮
    async onSubmit () {
      await this.$refs.form.validate()
      if (!this.detail.id) {
        await addSubjectApi({ ...this.detail, subjectID: +this.detail.subjectID })
        this.$message.success('添加成功')
      } else {
        await updateSubjectApi(this.detail)
        this.$message.success('修改成功')
      }
      this.$emit('get-directorys-list')
      this.closeDialog()
    },
    // 关闭弹框
    closeDialog () {
      this.$emit('close-dialog')
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang='less'></style>
